package com.wn.manpower.web;

import com.wn.common.PageBean;
import com.wn.common.ResponseEntity;
import com.wn.entity.ChangePosts;
import com.wn.entity.Dimission;
import com.wn.entity.Hr;
import com.wn.manpower.service.ChangePostsService;
import com.wn.manpower.service.DimissionService;
import com.wn.manpower.service.HumanResourcesService;
import com.wn.manpower.vo.ChangePostsVo;
import com.wn.manpower.vo.DimissionVo;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 离职申请
 * @author dzj
 * date: 2022/10/20
 */
@Slf4j
@RestController
@RequestMapping("/manpower/dimission")
public class DimissionController {

    @Autowired
    private DimissionService dimissionService;

    @Autowired
    private HumanResourcesService humanResourcesService;

    @RequestMapping("/add")
    public ResponseEntity add(@RequestBody DimissionVo dimissionVo, HttpServletRequest request) {
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        RuntimeService runtimeService = processEngine.getRuntimeService();
        String key = "dimission";

//       创建变量集合
        Map<String, Object> map1 = new HashMap<>();
//      设置user1的取值，用户可以在界面上设置流程的执行  申请人
        map1.put("user1", dimissionVo.getUser1());
        //下一个任务负责人
        Map<String, Object> map2 = new HashMap<>();
        map2.put("user2", dimissionVo.getUser2());
//        启动流程实例，并设置流程变量的值（把map1传入）        单独写个方法，同时调用并行执行
        ProcessInstance processInstance =
                runtimeService.startProcessInstanceByKey(key, map1);

        //通过界面传输的id获得hr实例，得知其名字
        int userId = Integer.parseInt(request.getHeader("userId"));
        Hr hr = humanResourcesService.getById(userId);
//        获取taskService  实例申请同时完成第一步
        TaskService taskService = processEngine.getTaskService();
        Task task = taskService.createTaskQuery()
                .processDefinitionKey(key) //流程Key
                .taskAssignee(hr.getWorkNumber())  //要查询的负责人
                .singleResult();
        //完成任务的时候设置下一个负责人  前端记得传输负责人
        taskService.complete(task.getId(), map2);
        log.debug("申请执行完成", "下一负责人" + dimissionVo.getUser2());

        //查询下一个负责人任务
        List<Task> tasks = taskService.createTaskQuery()
                .processDefinitionKey(key) //流程Key
                .taskAssignee(dimissionVo.getUser2())//只查询该任务负责人的任务
                .list();

        //处理完成后 查询出当前任务id加入到数据库表格
        dimissionVo.getDimission().setActivitiInstanceId(tasks.get(0).getId());
        dimissionService.add(dimissionVo.getDimission());

        return ResponseEntity.success;
    }


    /**
     * 查询当前个人待执行的任务,就是点击页面，直接展示自己的任务
     *
     * 通过用户id，获得当前用户的任务id
     * 通过任务id，多条件查询表格
     */
    @RequestMapping("/getTask")
    public ResponseEntity getTask(HttpServletRequest request) {
        String key = "dimission";
        //通过界面传输的id获得hr实例，得知其名字
        int userId = Integer.parseInt(request.getHeader("userId"));
        Hr hr = humanResourcesService.getById(userId);

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        List<Task> tasks = taskService.createTaskQuery()
                .processDefinitionKey(key) //流程Key
                .taskAssignee(hr.getName())//只查询该任务负责人的任务
                .list();

        List<Dimission> dimissionList = null;

        for (int i = 0; i < tasks.size(); i++) {
            //通过任务id查询数据
            Dimission dimission = dimissionService.getByActivitiInstanceId(tasks.get(i).getId());
            dimissionList.add(dimission);
        }

        return new ResponseEntity(dimissionList);
    }

    /**
     * 完成任务
     */
    @RequestMapping("/down")
    public ResponseEntity down(@RequestBody DimissionVo dimissionVo) {
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();

        Map<String, Object> map = new HashMap<>();
        map.put("user2", dimissionVo.getUser2());

        String key = "dimission";

//        完成任务,参数：任务id
        taskService.complete(dimissionVo.getDimission().getActivitiInstanceId(), map);

        //查询下一个负责人任务   此处查询，引使用流程实例id进行查询，而不是用负责人
        Task task = taskService.createTaskQuery()
                .processDefinitionKey(key) //流程Key
                .taskAssignee(dimissionVo.getUser2())//只查询该任务负责人的任务
                .singleResult();  // singleResult 单个   list 多个

        dimissionVo.getDimission().setActivitiInstanceId(task.getId());
        dimissionService.update(dimissionVo.getDimission());

        return ResponseEntity.success;
    }


    @RequestMapping("/update")
    public ResponseEntity update(@RequestBody Dimission dimission) {
        dimissionService.update(dimission);
        return ResponseEntity.success;
    }

    @RequestMapping("/getById/{id}")
    public ResponseEntity getById(@PathVariable int id) {
        Dimission dimission = dimissionService.getById(id);
        return new ResponseEntity(dimission);
    }

    @RequestMapping("/getPageByCondition")
    public ResponseEntity getByCondition(@RequestBody DimissionVo dimissionVo) {
        PageBean<Dimission> pageBean = dimissionService.getPageByCondition(dimissionVo.getDimission(), dimissionVo.getCurrPage(), dimissionVo.getPageSize());
        return new ResponseEntity(pageBean);
    }

    @RequestMapping("/del/{id}")
    public ResponseEntity del(@PathVariable int id) {
        dimissionService.del(id);
        return ResponseEntity.success;
    }
}
